package com.survey.demo.manager;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import java.util.ArrayList;
import java.util.List;

public class RecordDao {
    private SQLiteDatabase db;

    public RecordDao() {
        this.db = RecordSQLiteOpenHelper.getDatabase();
    }
    /**
     * 插入数据
     */
    public void insertData(String tempName) {
        db = RecordSQLiteOpenHelper.getDatabase();
        db.execSQL("insert into records(name) values('" + tempName + "')");
        db.close();
    }

    /**
     * 模糊查询数据
     */
    public  List<String> queryData(String tempName) {
        db = RecordSQLiteOpenHelper.getDatabase();
        Cursor cursor = db.rawQuery("select * from records where name like '%" + tempName + "%' order by _id desc ", null);
        int nameIndex = 0;
        List<String> personList = null;
        if(cursor.getCount() >= 0) {
            nameIndex = cursor.getColumnIndex("name");
            personList = new ArrayList<String>();
        }
        while(cursor.moveToNext()) {
            String name = cursor.getString(nameIndex);
            personList.add(name);
        }
        return personList;
    }

    /**
     * 检查数据库中是否已经有该条记录
     */
    public boolean hasData(String tempName) {
        db = RecordSQLiteOpenHelper.getDatabase();
        Cursor cursor = db.rawQuery(
                "select * from records where name =?", new String[]{tempName});
        //判断是否有下一个
        return cursor.moveToNext();
    }

    /**
     * 清空数据
     */
    public void deleteData() {
        db = RecordSQLiteOpenHelper.getDatabase();
        db.execSQL("delete from records");
        db.close();
    }
}
